package com.roger.homecenterscreen.ui.viewmodel

import android.content.Context
import android.location.LocationListener
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.roger.homecenterscreen.data.location.LocationData
import com.roger.homecenterscreen.data.location.LocationService
import com.roger.homecenterscreen.data.location.IpLocationService
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class LocationViewModel(context: Context) : ViewModel() {
    
    private val locationService = LocationService(context)
    private val ipLocationService = IpLocationService()
    private var locationListener: LocationListener? = null
    
    private val _locationData = MutableStateFlow<LocationData?>(null)
    val locationData: StateFlow<LocationData?> = _locationData.asStateFlow()
    
    private val _isGettingLocation = MutableStateFlow(false)
    val isGettingLocation: StateFlow<Boolean> = _isGettingLocation.asStateFlow()
    
    private val _locationError = MutableStateFlow<String?>(null)
    val locationError: StateFlow<String?> = _locationError.asStateFlow()
    
    private val _hasLocationPermission = MutableStateFlow(false)
    val hasLocationPermission: StateFlow<Boolean> = _hasLocationPermission.asStateFlow()
    
    /**
     * 设置位置权限状态
     */
    fun setLocationPermission(granted: Boolean) {
        _hasLocationPermission.value = granted
        if (granted) {
            getCurrentLocation()
        }
    }
    
    /**
     * 直接设置位置数据（供外部增强服务使用）
     */
    fun setLocationData(location: LocationData) {
        _locationData.value = location
        _isGettingLocation.value = false
        _locationError.value = null
    }
    
    /**
     * 获取当前位置
     */
    fun getCurrentLocation() {
        if (!_hasLocationPermission.value) {
            // 如果没有位置权限，尝试使用IP定位
            tryIpLocation()
            return
        }
        
        viewModelScope.launch {
            _isGettingLocation.value = true
            _locationError.value = null
            
            // 先尝试获取最后已知位置（快速）
            locationService.getLastKnownLocation()
                .onSuccess { location ->
                    _locationData.value = location
                }
                .onFailure {
                    // 如果没有最后已知位置，再获取当前位置
                }
            
            // 获取当前精确位置
            locationService.getCurrentLocation()
                .onSuccess { location ->
                    _locationData.value = location
                    _isGettingLocation.value = false
                }
                .onFailure { exception ->
                    // GPS定位失败，尝试IP定位作为备用
                    _locationError.value = "GPS定位失败，尝试网络定位..."
                    tryIpLocationAfterGPSFailed()
                }
        }
    }
    
    /**
     * 尝试IP定位（无需权限）
     */
    private fun tryIpLocation() {
        viewModelScope.launch {
            _isGettingLocation.value = true
            _locationError.value = null
            
            // 尝试主要IP定位服务
            ipLocationService.getLocationByIP()
                .onSuccess { location ->
                    _locationData.value = location
                    _isGettingLocation.value = false
                }
                .onFailure {
                    // 主要服务失败，尝试备用服务
                    ipLocationService.getLocationByIPBackup()
                        .onSuccess { location ->
                            _locationData.value = location
                            _isGettingLocation.value = false
                        }
                        .onFailure { exception ->
                            _locationError.value = "网络定位失败: ${exception.message}"
                            _isGettingLocation.value = false
                        }
                }
        }
    }
    
    /**
     * GPS失败后尝试IP定位
     */
    private fun tryIpLocationAfterGPSFailed() {
        viewModelScope.launch {
            ipLocationService.getLocationByIP()
                .onSuccess { location ->
                    _locationData.value = location
                    _locationError.value = "已切换到网络定位"
                    _isGettingLocation.value = false
                }
                .onFailure {
                    ipLocationService.getLocationByIPBackup()
                        .onSuccess { location ->
                            _locationData.value = location
                            _locationError.value = "已切换到网络定位"
                            _isGettingLocation.value = false
                        }
                        .onFailure { exception ->
                            _locationError.value = "所有定位方式都失败了"
                            _isGettingLocation.value = false
                        }
                }
        }
    }
    
    /**
     * 重新获取位置
     */
    fun refreshLocation() {
        getCurrentLocation()
    }
    
    /**
     * 清除位置错误
     */
    fun clearLocationError() {
        _locationError.value = null
    }
    
    /**
     * 获取位置的描述信息
     */
    fun getLocationDescription(): String {
        return _locationData.value?.getLocationDescription() ?: "未知位置"
    }
    
    /**
     * 获取和风天气格式的位置字符串
     */
    fun getLocationForWeatherApi(): String? {
        return _locationData.value?.toQWeatherFormat()
    }
    
    override fun onCleared() {
        super.onCleared()
        // 清理位置监听器
        locationListener?.let { listener ->
            locationService.stopLocationUpdates(listener)
        }
    }
} 